﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Colorful.Database;
using Colorful.Models;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;

namespace Colorful.CMS.Core.Controllers.Admin
{
    [MyAuth(PermissionEnum.Admin)]
    public class GuestbookController : AdminBaseController
    {
        #region 初始化
        public IActionResult Index(long mid, int? sort)
        {
            if (mid == 0)
                return this.GetTextResult("菜单不能为空！");
            if (!this.HasMenu(mid))
                return this.GetTextResult("无菜单访问权限！");
            ViewData["MenuId"] = mid;
            ViewData["DataUrl"] = this.GetUrl("guestbook/list");
            ViewData["DelUrl"] = this.GetUrl("guestbook/del");
            return View();
        }
        #endregion

        #region 获取留言列表
        [Route("guestbook/list")]
        public IActionResult GetCodeList(string keyword, string startDate, string endDate)
        {
            using (var db = CMSDbHelper.GetDb())
            {
                var query = db.Guestbooks.GetQuery();
                if (!string.IsNullOrEmpty(keyword))
                    query = query.Where(a => a.Email.Contains(keyword) || a.Name.Contains(keyword) || a.Phone.Contains(keyword) || a.Message.Contains(keyword));
                if (!string.IsNullOrEmpty(startDate))
                {
                    var sdate = (startDate.ParseDate() ?? DateTime.Now).MinDate();
                    var edate = (endDate.ParseDate() ?? DateTime.Now).MaxDate();
                    query = query.Where(a => a.AddDate >= sdate && a.AddDate <= edate);
                }
                return this.GetDataGrid(query.OrderByDescending(a => a.AddDate).Select(a => new { a.Id, a.Name, a.Email, a.Phone, a.AddDate, a.Message }));
            }
        }
        #endregion

        #region 删除留言
        [Route("guestbook/del")]
        public IActionResult Delete(long menuId, string[] ids)
        {
            if (!this.HasPermission(PermissionEnum.Delete))
                return this.GetResult(new Exception("无操作权限！"));
            if (!this.HasMenu(menuId))
                return this.GetResult(false, "无访问权限！");
            try
            {
                using (var db = CMSDbHelper.GetDb())
                {
                    db.Guestbooks.Delete(a => ids.Contains(a.Id));
                    return this.GetResult(true);
                }
            }
            catch (Exception ex)
            {
                return this.GetResult(ex);
            }
        }
        #endregion
    }
}